package com.dyp.content_negotiation.ctr;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class ReportCtr {

    //只在该Ctr内生效
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // 1. 获取请求头中的格式
        String dateFormat = request.getHeader("X-Date-Format");

        // 2. 动态注册编辑器
        if ("dd/MM/yyyy".equals(dateFormat)) {
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
        } else {
            // 默认格式
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        }
    }

    @GetMapping("/report")
    public String getReport(@RequestHeader("X-Date-Format") String dateFormat,
                            @RequestParam Date startDate,
                            @RequestParam Date endDate) {
        // 根据请求头格式自动转换日期参数
        return "report";
    }
}
